//
//  OpenShare+Alipay.m
//  openshare
//
//  Created by LiuLogan on 15/6/4.
//  Copyright (c) 2015年 OpenShare <http://openshare.gfzj.us/>. All rights reserved.
//

#import "OpenShare+Alipay.h"
#import <AlipaySDK/AlipaySDK.h>
@implementation OpenShare (Alipay)
static NSString* schema=@"Alipay";
/**
 *  支付宝支付参数都是从服务器获得的，所以不需要注册key。但是还是需要先connect向OpenShare注册，以便回调。
 */
+(void)connectAlipay{
    [self set:schema Keys:@{@"schema":schema}];
}

+(BOOL)isAlipayInstalled{
    return [self canOpen:@"alipay://"];
}
+(void)AliPay:(NSString*)link fromScheme:(NSString *)fromScheme Success:(paySuccess)success Fail:(payFail)fail{
    [self setPaySuccessCallback:success];
    [self setPayFailCallback:fail];
//    if ([self isAlipayInstalled]) {
//        //支付宝为了用户体验，会把截屏放在支付的后面当背景，可选项。当然也可以用其他的自己生成的UIImage，比如[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Default@2x" ofType:@"png"]]
//        UIImage *screenShot= [self screenshot];
//        //获取到fromAppUrlScheme，来设置截屏。
//        NSString *linkStr=[self urlDecode:[link substringFromIndex:NSMaxRange([link rangeOfString:@"?"])]];
//        NSDictionary *linkDic=[NSJSONSerialization JSONObjectWithData:[linkStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
//        [[UIPasteboard generalPasteboard] setData:[NSKeyedArchiver archivedDataWithRootObject:@{@"image_data" :UIImagePNGRepresentation(screenShot),@"scheme" :linkDic[@"fromAppUrlScheme"]}] forPasteboardType:@"com.alipay.alipayClient.screenImage"];
//        //END 设置截屏(可以不设置,注释掉这块代码即可。)。
//
//        [self openURL:link];
//    }
   [OpenShare setOpenURL:[NSURL URLWithString:@"Alipay://openUrl/safepay"]];
    [[AlipaySDK defaultService] payOrder:link fromScheme:fromScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"----- %@",resultDic);
        NSInteger resultCode = [resultDic[@"resultStatus"] integerValue];
        switch (resultCode) {
            case 9000:{     //支付成功
                if ([self paySuccessCallback]) {
                    [self paySuccessCallback](resultDic);
                }
            }
            break;
            case 6001:{     //支付取消
                if ([self payFailCallback]) {
                    NSError *err = [[NSError alloc] initWithDomain:@"alipay_pay" code:-1 userInfo:resultDic];
                    [self payFailCallback](resultDic, err);
                }
            }
            break;
            default:{        //支付失败
                if ([self payFailCallback]) {
                    NSError *err = [[NSError alloc] initWithDomain:@"alipay_pay" code:-999 userInfo:resultDic];
                    [self payFailCallback](resultDic,err);
                }
            }
            break;
        }
    }];
}
+(BOOL)Alipay_handleOpenURL{
    NSURL* url=[self returnedURL];
    if ([url.absoluteString rangeOfString:@"//safepay/"].location != NSNotFound) {
//        NSError *err;
//        NSDictionary *ret=[NSJSONSerialization JSONObjectWithData:[[self urlDecode:url.query]dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&err];
//        if (err||ret[@"memo"]==[NSNull null]||[ret[@"memo"][@"ResultStatus"] intValue]!=9000) {
//            if ([self payFailCallback]) {
//                [self payFailCallback](ret,err?:[NSError errorWithDomain:@"alipay_pay" code:ret[@"memo"]!=[NSNull null]?[ret[@"memo"][@"ResultStatus"] intValue]:-1 userInfo:ret]);
//            }
//        }else{
//            if ([self paySuccessCallback]) {
//                [self paySuccessCallback](ret);
//            }
//        }
        if ([url.absoluteString rangeOfString:@"openUrl_mlx"].location != NSNotFound) {
            if ([self payFailCallback]) {
                [self payFailCallback](nil,nil);
            }
            return YES;
        }
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            //【由于在跳转支付宝客户端支付的过程中，商户app在后台很可能被系统kill了，所以pay接口的callback就会失效，请商户对standbyCallback返回的回调结果进行处理,就是在这个方法里面处理跟callback一样的逻辑】
            NSLog(@"result = %@",resultDic);
            
            NSInteger resultCode = [resultDic[@"resultStatus"] integerValue];
            switch (resultCode) {
                case 9000:{//支付成功
                    if ([self paySuccessCallback]) {
                        [self paySuccessCallback](resultDic);
                    }
                }
                    break;
                    
                case 6001:{    //支付取消
                    if ([self payFailCallback]) {
                        NSError *err = [[NSError alloc] initWithDomain:@"alipay_pay" code:-1 userInfo:resultDic];
                        [self payFailCallback](resultDic, err);
                    }
                }
                break;
                default:{  //支付失败
                    if ([self payFailCallback]) {
                        NSError *err;
                        NSDictionary *ret=[NSJSONSerialization JSONObjectWithData:[[self urlDecode:url.query]dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&err];
                    [self payFailCallback](resultDic,err?:[NSError errorWithDomain:@"alipay_pay" code:ret[@"memo"]!=[NSNull null]?[ret[@"memo"][@"ResultStatus"] intValue]:-1 userInfo:ret]);
                    }
                }
                    break;
            }
        }];
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        return YES;
    }else{
        return NO;
    }
}
@end
